package com.dupf.product.web.controller.product;

import com.dupf.common.base.BaseController;
import com.dupf.common.util.ItvJsonUtil;
import com.dupf.product.common.constant.ProductResult;
import com.dupf.product.common.constant.ProductResultConstant;
import com.dupf.product.dao.model.ProductLogisticsCompany;
import com.dupf.product.dao.model.ProductLogisticsCompanyExample;
import com.dupf.product.dao.model.ProductLogisticsPrice;
import com.dupf.product.dao.model.ProductLogisticsPriceExample;
import com.dupf.product.rpc.api.ProductLogisticsCompanyService;
import com.dupf.product.rpc.api.ProductLogisticsPriceService;
import com.dupf.upms.common.constant.UpmsResult;
import com.dupf.upms.common.constant.UpmsResultConstant;
import com.google.common.base.Splitter;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 产品controller
 * Created by dupf on 2018/3/20.
 */
@Controller
@Api(value = "系统设置", description = "物流设置")
@RequiresPermissions("system_logistics")
@RequestMapping("/system/logistics")
public class ProductLogisticsController extends BaseController {

    private static final Logger LOGGER = LoggerFactory.getLogger(ProductLogisticsController.class);

    @Autowired
    private ProductLogisticsCompanyService productLogisticsCompanyService;

    @Autowired
    private ProductLogisticsPriceService productLogisticsPriceService;

    @ApiOperation(value = "物流公司列表")
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    @ResponseBody
    public Object list(
            @RequestParam(required = false, defaultValue = "0", value = "offset") int offset,
            @RequestParam(required = false, defaultValue = "100", value = "limit") int limit,
            HttpServletRequest request
    ) {

        Integer orgId = (Integer) request.getAttribute("currentOrgId");

        ProductLogisticsCompanyExample productLogisticsCompanyExample = new ProductLogisticsCompanyExample();
        productLogisticsCompanyExample.createCriteria().andOrgidIn(Arrays.asList(orgId));

        List<ProductLogisticsCompany> rows = productLogisticsCompanyService.selectByExampleForOffsetPage(productLogisticsCompanyExample, offset, limit);
        long total = productLogisticsCompanyService.countByExample(productLogisticsCompanyExample);
        Map<String, Object> result = new HashMap<>();
        result.put("list", rows);
        result.put("total", total);
        return new ProductResult(ProductResultConstant.SUCCESS, result);
    }

    @ApiOperation(value = "添加物流公司")
    @RequestMapping(value = "/create", method = RequestMethod.POST)
    @ResponseBody
    public Object create(HttpServletRequest request) throws IOException {
        Integer orgId = (Integer) request.getAttribute("currentOrgId");

        String requestStr = super.getInputStream(request);
        JSONObject data = JSONObject.fromObject(requestStr);

        String title = data.getString("title");
        String description = data.optString("description");

        ProductLogisticsCompanyExample productLogisticsCompanyExample = new ProductLogisticsCompanyExample();
        productLogisticsCompanyExample.createCriteria().andTitleEqualTo(title);

        int count = productLogisticsCompanyService.countByExample(productLogisticsCompanyExample);
        if (count > 0) {
            return new ProductResult(ProductResultConstant.EXISTED, "该物流已存在");
        }

        ProductLogisticsCompany productLogisticsCompany = new ProductLogisticsCompany();
        productLogisticsCompany.setTitle(title);
        productLogisticsCompany.setDescription(description);
        // 暂定全部是平台默认的
        productLogisticsCompany.setOrgid(orgId);
        productLogisticsCompany.setCtime(System.currentTimeMillis());

        productLogisticsCompanyService.insertSelective(productLogisticsCompany);

        return new ProductResult(ProductResultConstant.SUCCESS, productLogisticsCompany.getId());
    }

    @ApiOperation(value = "删除物流公司")
    @RequestMapping(value = "/delete/{ids}", method = RequestMethod.GET)
    @ResponseBody
    public Object delete(@PathVariable("ids") String ids, HttpServletRequest request) throws IOException {

        int count = productLogisticsCompanyService.deleteByPrimaryKeys(ids);
        return new UpmsResult(UpmsResultConstant.SUCCESS, count);
    }

    @ApiOperation(value = "修改物流公司")
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    @ResponseBody
    public Object update(HttpServletRequest request) throws IOException {

        Integer orgId = (Integer) request.getAttribute("currentOrgId");

        String requestStr = super.getInputStream(request);
        JSONObject data = JSONObject.fromObject(requestStr);

        Integer id = data.getInt("id");
        String title = data.getString("title");
        String description = data.optString("description");

        ProductLogisticsCompanyExample productLogisticsCompanyExample = new ProductLogisticsCompanyExample();
        productLogisticsCompanyExample.createCriteria().andTitleEqualTo(title).andIdNotEqualTo(id);

        int count = productLogisticsCompanyService.countByExample(productLogisticsCompanyExample);
        if (count > 0) {
            return new ProductResult(ProductResultConstant.EXISTED, "该物流已存在");
        }

        ProductLogisticsCompany productLogisticsCompany = new ProductLogisticsCompany();
        productLogisticsCompany.setTitle(title);
        productLogisticsCompany.setDescription(description);
        // 暂定全部是平台默认的
        productLogisticsCompany.setOrgid(orgId);
        productLogisticsCompany.setId(id);

        productLogisticsCompanyService.updateByPrimaryKeySelective(productLogisticsCompany);

        return new ProductResult(ProductResultConstant.SUCCESS, productLogisticsCompany.getId());
    }

    @ApiOperation(value = "物流价格列表")
    @RequestMapping(value = "/price/list/{logisticsId}", method = RequestMethod.GET)
    @ResponseBody
    public Object priceList(@PathVariable(value = "logisticsId") Integer logisticsId, HttpServletRequest request) {

        Integer orgId = (Integer) request.getAttribute("currentOrgId");

        ProductLogisticsPriceExample example = new ProductLogisticsPriceExample();
        example.createCriteria().andOrgIdIn(Arrays.asList(orgId)).andLogisticsIdEqualTo(logisticsId);
        example.setOrderByClause("weight ASC");

        List<ProductLogisticsPrice> rows = productLogisticsPriceService.selectByExample(example);
        return new ProductResult(ProductResultConstant.SUCCESS, rows);
    }

    @ApiOperation(value = "添加物流价格")
    @RequestMapping(value = "/price/create", method = RequestMethod.POST)
    @ResponseBody
    public Object priceCreate(HttpServletRequest request) throws IOException {
        Integer orgId = (Integer) request.getAttribute("currentOrgId");

        String requestStr = super.getInputStream(request);

        ProductLogisticsPrice productLogisticsPrice = ItvJsonUtil.readValue(requestStr, ProductLogisticsPrice.class);
        productLogisticsPrice.setOrgId(orgId);

        Float weight = productLogisticsPrice.getWeight();

        ProductLogisticsPriceExample example = new ProductLogisticsPriceExample();
        example.createCriteria().andWeightEqualTo(weight).andOrgIdEqualTo(orgId);

        int count = productLogisticsPriceService.countByExample(example);
        if (count > 0) {
            return new ProductResult(ProductResultConstant.EXISTED, "该重量已存在");
        }

        productLogisticsPrice.setCtime(System.currentTimeMillis());

        productLogisticsPriceService.insertSelective(productLogisticsPrice);

        return new ProductResult(ProductResultConstant.SUCCESS, productLogisticsPrice.getId());
    }

    @ApiOperation(value = "删除物流价格")
    @RequestMapping(value = "/price/delete/{ids}", method = RequestMethod.GET)
    @ResponseBody
    public Object priceDelete(@PathVariable("ids") String ids, HttpServletRequest request) throws IOException {

        Integer orgId = (Integer) request.getAttribute("currentOrgId");

        if (StringUtils.isEmpty(ids)) {
            return new UpmsResult(UpmsResultConstant.SUCCESS, 0);
        }

        ProductLogisticsPriceExample example = new ProductLogisticsPriceExample();
        example.createCriteria().andOrgIdEqualTo(orgId).andIdIn(Splitter.on(',').trimResults().omitEmptyStrings()
                .splitToList(ids).stream().map(Integer::valueOf).collect(Collectors.toList()));

        int count = productLogisticsPriceService.deleteByPrimaryKeys(ids);
        return new UpmsResult(UpmsResultConstant.SUCCESS, count);
    }

    @ApiOperation(value = "修改物流价格")
    @RequestMapping(value = "/price/update", method = RequestMethod.POST)
    @ResponseBody
    public Object priceUpdate(HttpServletRequest request) throws IOException {
        Integer orgId = (Integer) request.getAttribute("currentOrgId");

        String requestStr = super.getInputStream(request);

        ProductLogisticsPrice productLogisticsPrice = ItvJsonUtil.readValue(requestStr, ProductLogisticsPrice.class);
        productLogisticsPrice.setOrgId(orgId);

        Float weight = productLogisticsPrice.getWeight();

        if (weight != null) {
            ProductLogisticsPriceExample example = new ProductLogisticsPriceExample();
            example.createCriteria().andWeightEqualTo(weight).andOrgIdEqualTo(orgId).andLogisticsIdEqualTo(productLogisticsPrice.getLogisticsId());

            int count = productLogisticsPriceService.countByExample(example);
            if (count > 0) {
                return new ProductResult(ProductResultConstant.EXISTED, "该重量已存在");
            }
        }

        productLogisticsPriceService.updateByPrimaryKeySelective(productLogisticsPrice);

        return new ProductResult(ProductResultConstant.SUCCESS, productLogisticsPrice.getId());
    }
}